package com.tensquare.friend.interceptor;

import com.netflix.discovery.converters.Auto;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by WF on 2019/9/24 10:46
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //1.得到请求头
        String header = request.getHeader("Authorization");
        //2.判断请求头是否以Bearer 开头
        if(StringUtils.isNotBlank(header) && header.startsWith("Bearer ")){
            //2.1)从第七位开始截取到结束，代表token的值
            String token = header.substring(7);
            //2.2)解析token
            Claims claims = jwtUtil.parseJwt(token);
            //2.3)判断是否存在
            if(claims != null){
                request.setAttribute("claims",claims);
            }
        }
        return true;
    }
}
